package org.algorithm.Backtracking.leetcode47;

import javax.print.DocFlavor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {

    /**
     * 全排列，数组中含有重复元素，需要考虑横向去重
     */

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> item = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        int n = nums.length;
        boolean [] used = new boolean[n];
        Arrays.sort(nums);
        Arrays.fill(used,false);
        backtracking(nums,used);
        return res;
    }

    private void  backtracking(int [] nums,boolean [] used){
        if (item.size()==nums.length){
            res.add(new ArrayList<>(item));
            return;
        }

        for (int i = 0; i < nums.length; i++) {

            if (i>0 && nums[i]==nums[i-1] && !used[i-1]){
                continue;
            }

            if (!used[i]){
                item.add(nums[i]);
                used[i]=true;
                backtracking(nums,used);
                used[i]=false;
                item.remove(item.size()-1);
            }

        }
    }
}
